<template>
  <view class="analysis-input-container">
    <view class="main-content">
      <view class="upload-grid">
        <view class="upload-card">
          <view class="section-title">点击上传简介图片</view>
          <view class="upload-box" @click="pickImage('context')">
            <image v-if="contextImage" :src="contextImage" class="preview" mode="aspectFit" />
            <view v-else class="placeholder">
              <text class="plus">＋</text>
              <text class="hint">点击上传</text>
              <text class="sub">建议3:4</text>
            </view>
          </view>
        </view>
        <view class="upload-card">
          <view class="section-title">点击上传作品图片</view>
          <view class="upload-box" @click="pickImage('exhibition')">
            <image v-if="exhibitionImage" :src="exhibitionImage" class="preview" mode="aspectFit" />
            <view v-else class="placeholder">
              <text class="plus">＋</text>
              <text class="hint">点击上传</text>
              <text class="sub">建议3:4</text>
            </view>
          </view>
        </view>
      </view>
      


      <view class="analysis-section">
        <button class="analysis-btn" @click="startAnalysis" :loading="isAnalyzing">
          {{ isAnalyzing ? '分析中...' : '开始分析' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { difyCreateChatMessage } from '@/services/api/backendApi'

const isAnalyzing = ref(false)
// 预设图片数据（新接口直接使用URL，不需要upload_file_id）
const PRESET_CONTEXT = { 
  url: 'https://douyin-ai.tos-cn-shanghai.volces.com/context1.jpg'
}
const PRESET_EXHIBITION_1 = { 
  url: 'https://douyin-ai.tos-cn-shanghai.volces.com/context2.jpg'
}
const contextImage = ref(PRESET_CONTEXT.url)
const exhibitionImage = ref(PRESET_EXHIBITION_1.url)
const isPresetContext = ref(true)
const isPresetExhibition = ref(true)

function pickImage(type) {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      const filePath = res.tempFilePath || res.tempFilePaths?.[0]
      if (!filePath) return
      if (type === 'context') {
        contextImage.value = filePath
        isPresetContext.value = false
      } else if (type === 'exhibition') {
        exhibitionImage.value = filePath
        isPresetExhibition.value = false
      }
    }
  })
}

async function startAnalysis() {
  if (!contextImage.value || !exhibitionImage.value) {
    uni.showToast({ title: '请先上传两张图片', icon: 'none' })
    return
  }
  
  // 检查网络状态
  const networkType = await getNetworkType()
  console.log('当前网络类型:', networkType)
  
  if (networkType === 'none') {
    uni.showToast({ 
      title: '网络连接失败，请检查网络设置', 
      icon: 'none' 
    })
    return
  }
  
  isAnalyzing.value = true
  try {
    const userId = uni.getStorageSync('userId') || 1
    
    // 新接口：直接使用图片URL，不需要上传获取upload_file_id
    console.log('=== 开始AI分析流程 ===');
    console.log('用户ID:', userId);
    console.log('简介图片URL:', contextImage.value);
    console.log('作品图片URL:', exhibitionImage.value);
    console.log('是否使用预设简介图片:', isPresetContext.value);
    console.log('是否使用预设作品图片:', isPresetExhibition.value);
    
    // 直接使用图片URL调用Dify API
    console.log('开始调用Dify本地API进行分析...');
    console.log('首次分析参数:', {
      contextImageUrl: contextImage.value,
      exhibitionImageUrl: exhibitionImage.value,
      userId,
      useContext: true,
      conversationId: '' // 首次分析，conversationId为空
    })
    
    const resp = await difyCreateChatMessage({
      contextImageUrl: contextImage.value,
      exhibitionImageUrl: exhibitionImage.value,
      userId,
      useContext: true
    })
    
    console.log('Dify API 分析成功:', resp);
    
    // 传给结果页
    uni.navigateTo({
              url: `/pages/ai-explore/analysis-result?answer=${encodeURIComponent(resp.answer || '')}&contextImageUrl=${encodeURIComponent(contextImage.value)}&conversationId=${encodeURIComponent(resp.conversation_id || '')}`
    })
  } catch (e) {
    console.error('分析失败:', e)
    
    // 根据错误类型显示不同的提示
    let errorMessage = '分析失败，请重试'
    if (e.message && e.message.includes('网络连接问题')) {
      errorMessage = '网络连接不稳定，请检查网络后重试'
    } else if (e.message && e.message.includes('HTTP/2 stream')) {
      errorMessage = '网络连接中断，请重试'
    }
    
    uni.showToast({ 
      title: errorMessage, 
      icon: 'none',
      duration: 3000
    })
  } finally {
    isAnalyzing.value = false
  }
}

// 获取网络状态
function getNetworkType() {
  return new Promise((resolve) => {
    uni.getNetworkType({
      success: (res) => {
        resolve(res.networkType)
      },
      fail: () => {
        resolve('unknown')
      }
    })
  })
}

// 页面加载时处理URL参数
onMounted(() => {
  console.log('analysis-input页面已挂载');
  
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  
  console.log('页面参数:', options);
  
  // 如果URL中有imageUrl参数，自动设置为作品图片
  if (options.imageUrl) {
    try {
      const imageUrl = decodeURIComponent(options.imageUrl)
      exhibitionImage.value = imageUrl
      isPresetExhibition.value = false
      console.log('从导航栏传入的图片URL:', imageUrl)
      console.log('图片已设置为:', exhibitionImage.value)
    } catch (error) {
      console.error('解析图片URL失败:', error)
      uni.showToast({ 
        title: '图片URL解析失败', 
        icon: 'none' 
      })
    }
  } else {
    console.log('未检测到imageUrl参数，使用预设图片')
    // 在开发者工具中，如果没有传入图片，提示用户这是演示模式
    if (isDevTools()) {
      console.log('开发者工具模式：使用预设图片进行演示')
    }
  }
})

// 检测是否在开发者工具中
function isDevTools() {
  try {
    if (typeof uni !== 'undefined' && uni.getSystemInfoSync) {
      const systemInfo = uni.getSystemInfoSync();
      return systemInfo.platform === 'devtools';
    }
    return false;
  } catch (error) {
    return false;
  }
}
</script>

<style lang="scss">
.analysis-input-container {
  min-height: 100vh;
  background: #1a1a1a;
  padding-bottom: 40px;
}

.main-content { padding: 20px; }

.upload-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.upload-card { background: rgba(255,255,255,0.8); border-radius: 14px; padding: 16px; }
.section-title { font-size: 16px; font-weight: 600; color: #ffffff; margin-bottom: 10px; }

.upload-box {
  height: 180px;
  border: 2px dashed rgba(212,175,55,0.5);
  border-radius: 12px;
  background: linear-gradient(135deg, rgba(255,255,255,0.9), rgba(245,242,237,0.85));
  display: flex; align-items: center; justify-content: center; overflow: hidden;
}
.placeholder { display: flex; flex-direction: column; align-items: center; color: #ffffff; }
.plus { font-size: 28px; line-height: 1; margin-bottom: 6px; }
.hint { font-size: 14px; font-weight: 600; }
.sub { font-size: 12px; color: #a0826d; margin-top: 2px; }
.preview { width: 100%; height: 100%; object-fit: contain; }

.analysis-section { text-align: center; margin-top: 18px; }
.analysis-btn {
  background: linear-gradient(135deg, #ff0050, #ff4081);
  color: #ffffff; border: none; border-radius: 25px; padding: 15px 40px;
  font-size: 18px; font-weight: 600;
}
</style>
